/**
 * @file implements AsyncTask class
 * @author CORSAIR <vladimir.corsair@gmail.com>
 * @version 1.5.0 test
 */

/**
 * Send ajax request
 * @returns {AsyncTask}
 */
var AsyncTask = function () {
    this.xmlHTTPRequests = [];
    this.names = [];
};

/**
 * Create POST ajax
 * @param {String} name of the request
 * @param {String} path url for request
 * @returns {AsyncTask.prototype.create.Anonym$0}
 */
AsyncTask.prototype.POST = function (name, path) {
    return this.create(name, path, "POST");
};

/**
 * Create GET ajax
 * @param {String} name of the request
 * @param {String} path url for request
 * @returns {AsyncTask.prototype.create.Anonym$0}
 */
AsyncTask.prototype.GET = function (name, path) {
    return this.create(name, path, "GET");
};

/**
 * Create new task by name
 * @param {String} name of the request
 * @param {String} path url for request
 * @param {String} type GET or POST
 * @returns {AsyncTask.prototype.create.Anonym$0}
 */
AsyncTask.prototype.create = function (name, path, type) {
    this.xmlHTTPRequests[name] = new XMLHttpRequest();
    this.names[name] = new EventSet();
    this.names[name].add('change');
    this.names[name].add('complete');
    this.xmlHTTPRequests[name].open(type, path, true);
    return this.names[name];
};

/**
 * Send created request by name
 * @param {String} name
 * @param {String} args
 * @returns {EventSet}
 */
AsyncTask.prototype.send = function (name, args) {
    var time = (new Date()).getTime();
    this.xmlHTTPRequests[name].onreadystatechange = (function () {
        var interval = (new Date()).getTime() - time;
        if (this.xmlHTTPRequests[name].readyState === 4 && this.xmlHTTPRequests[name].status === 200) {
            this.names[name].fire('complete', this.xmlHTTPRequests[name].responseText, interval);
        } else {
            this.names[name].fire('change', this.xmlHTTPRequests[name].readyState, interval);
        }
    }).bind(this);
    
    this.xmlHTTPRequests[name].send(this.formatArguments(args));
    
    return this.names[name];
};

/**
 * Format JSON Object to GET parameters
 * @param {Object} args
 * @returns {String} formated string with arguments
 */
AsyncTask.prototype.formatArguments = function (args) {
    var r = [];
    for(var k in args) {
        r.push(k+"="+args[k]);
    }
    return r.join("&");
};